package com.sunday.shoufen.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.StringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.GradationScrollView;
import com.sunday.common.widgets.MyRatingBar;
import com.sunday.common.widgets.banner.ConvenientBanner;
import com.sunday.common.widgets.banner.holder.ViewHolderCreator;
import com.sunday.shoufen.R;
import com.sunday.shoufen.adapter.BannerHolder;
import com.sunday.shoufen.base.BaseApp;
import com.sunday.shoufen.base.NeedPhonePermissionActivity;
import com.sunday.shoufen.entity.ConfirmBuy;
import com.sunday.shoufen.entity.ShopSetDetail;
import com.sunday.shoufen.http.ApiClient;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/10/20.
 */

public class ShopSetDetailActivity extends NeedPhonePermissionActivity {


    @Bind(R.id.banner)
    ConvenientBanner banner;
    @Bind(R.id.product_title)
    TextView productTitle;
    @Bind(R.id.price_now)
    TextView priceNow;
    @Bind(R.id.price_old)
    TextView priceOld;
    @Bind(R.id.product_sale_num)
    TextView productSaleNum;
    @Bind(R.id.price_layout)
    RelativeLayout priceLayout;
    @Bind(R.id.shop_img)
    ImageView shopImg;
    @Bind(R.id.shop_name)
    TextView shopName;
    @Bind(R.id.ic_right)
    ImageView icRight;
    @Bind(R.id.shop_rating_bar)
    MyRatingBar shopRatingBar;
    @Bind(R.id.rating_score)
    TextView ratingScore;
    @Bind(R.id.shop_desc)
    TextView shopDesc;
    @Bind(R.id.shop_distance)
    TextView shopDistance;
    @Bind(R.id.shop_addr)
    TextView shopAddr;
    @Bind(R.id.btn_phone)
    ImageView btnPhone;
    @Bind(R.id.service_content)
    TextView serviceContent;
    @Bind(R.id.scrollview)
    GradationScrollView scrollview;
    @Bind(R.id.buy_now)
    TextView buyNow;
    @Bind(R.id.bottom_layout)
    LinearLayout bottomLayout;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title_layout)
    RelativeLayout titleLayout;

    @Bind(R.id.buy_num)
    TextView buyNum;
    @Bind(R.id.rl_shop)
    RelativeLayout rlShop;

    private long productId, memberId;
    private int type;//是否是活动商铺；0:普通 1:活动
    private ShopSetDetail shopSetDetail;
    private String lati, longti;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_set_detail);
        ButterKnife.bind(this);
        productId = getIntent().getLongExtra("productId", 0);
        lati = BaseApp.getInstance().getLatitude();
        longti = BaseApp.getInstance().getLongitude();
        type = getIntent().getIntExtra("type", 0);
        memberId = BaseApp.getInstance().getMember().getId();
        getData();

    }

    @Override
    public boolean onRequestCallPermissionSuccessed() {
        String number = shopSetDetail.getSellerInfo().getMobile();
        if (TextUtils.isEmpty(number)) {
            // 提醒用户
            // 注意：在这个匿名内部类中如果用this则表示是View.OnClickListener类的对象，
            // 所以必须用MainActivity.this来指定上下文环境。
            ToastUtils.showToast(mContext, "号码不能为空");
        } else {
            // 拨号：激活系统的拨号组件
            Intent intent = new Intent(); // 意图对象：动作 + 数据
            intent.setAction(Intent.ACTION_CALL); // 设置动作
            Uri data = Uri.parse("tel:" + number); // 设置数据
            intent.setData(data);
            startActivity(intent); // 激活Activity组件
        }
        return true;


    }

    private void getData() {
        showLoadingDialog(0);
        Call<ResultDO<ShopSetDetail>> call = ApiClient.getApiAdapter().getProductDetail(productId, lati, longti);
        call.enqueue(new Callback<ResultDO<ShopSetDetail>>() {
            @Override
            public void onResponse(Call<ResultDO<ShopSetDetail>> call, Response<ResultDO<ShopSetDetail>> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    shopSetDetail = response.body().getResult();
                    updateView();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<ShopSetDetail>> call, Throwable t) {
                dissMissDialog();
            }
        });
    }

    private void updateView() {
        if (shopSetDetail == null) {
            return;
        }
        final List<String> bannerImgs = new ArrayList<>();
        if (shopSetDetail.getProductInfo().getImages() != null && shopSetDetail.getProductInfo().getImages().size() > 0) {
            bannerImgs.addAll(shopSetDetail.getProductInfo().getImages());
        }
        banner.getLayoutParams().width = DeviceUtils.getDisplay(mContext).widthPixels;
        banner.getLayoutParams().height = DeviceUtils.getDisplay(mContext).widthPixels * 5 / 6;
        banner.startTurning(3000);
        banner.setFocusable(true);
        banner.setFocusableInTouchMode(true);
        banner.requestFocus();
        banner.setPages(new ViewHolderCreator<BannerHolder>() {
            @Override
            public BannerHolder createHolder() {
                return new BannerHolder();
            }
        }, bannerImgs)
                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused});
        banner.notifyDataSetChanged();

        productTitle.setText(shopSetDetail.getProductInfo().getProductName());
        priceNow.setText("￥"+shopSetDetail.getProductInfo().getPrice());
        priceOld.setText("￥"+shopSetDetail.getProductInfo().getMarketPrice());
        priceOld.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        productSaleNum.setText("已售" + shopSetDetail.getProductInfo().getSaleCount());

        shopName.setText(shopSetDetail.getSellerInfo().getShopName());
        Glide.with(mContext)
                .load(shopSetDetail.getSellerInfo().getImage())
                .error(R.mipmap.ic_default)
                .into(shopImg);
        shopRatingBar.setRating((int) shopSetDetail.getSellerInfo().getScore(), R.drawable.rating_bar, false, 30);
        ratingScore.setText((int) shopSetDetail.getSellerInfo().getScore() + "分");
        shopDesc.setText(StringUtils.listToString(shopSetDetail.getSellerInfo().getTags()));
        shopDistance.setText(shopSetDetail.getSellerInfo().getDistance());
        shopAddr.setText(shopSetDetail.getSellerInfo().getAddress());
        serviceContent.setText(shopSetDetail.getProductInfo().getProductDesc());
    }

    private int buynum = 1;

    @OnClick({R.id.btn_phone, R.id.buy_now, R.id.rl_shop, R.id.ivAdd, R.id.ivReduce})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_phone:
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("温馨提示");
                builder.setMessage("确认拨打商家电话吗");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        checkCallPermission();

                    }
                });
                builder.show();
                break;
            case R.id.buy_now:
                buyNow();
                break;
            case R.id.rl_shop:
                Intent intent = new Intent(mContext, ShopDetailActivity.class);
                intent.putExtra("shopId", shopSetDetail.getSellerInfo().getShopId());
                mContext.startActivity(intent);
                break;
            case R.id.ivAdd:
                buynum++;
                buyNum.setText(String.valueOf(buynum));
                break;
            case R.id.ivReduce:
                if (buynum == 1) {
                    return;
                }
                buynum--;
                buyNum.setText(String.valueOf(buynum));
                break;
        }
    }

    private void buyNow() {
        showLoadingDialog(0);
        Call<ResultDO<ConfirmBuy>> call = ApiClient.getApiAdapter().buyNow(shopSetDetail.getSellerInfo().getShopId(), memberId, productId,
                buynum, null, null);
        call.enqueue(new Callback<ResultDO<ConfirmBuy>>() {
            @Override
            public void onResponse(Call<ResultDO<ConfirmBuy>> call, Response<ResultDO<ConfirmBuy>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0) {
                    intent = new Intent(mContext, OrderPayActivity.class);
                    intent.putExtra("proNum",buynum);
                    intent.putExtra("confirmBuy", response.body().getResult());
                    startActivity(intent);
                }
            }

            @Override
            public void onFailure(Call<ResultDO<ConfirmBuy>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

}
